import { Fragment, MouseEvent } from 'react'
import {
  Card,
  Button, 
  List,
  Avatar,
  Badge,
} from 'antd'
import { useRecoilValue, useSetRecoilState } from 'recoil';
import { notificationState } from '../../store/'

type INotification = {
  readonly id: string;
  title: string;
  desc: string,
  hasRead: boolean;
}

interface IProps {
  notificationsCount?: number;
  avatar?: string;
  displayName?: string;
  children?: any
}

function Notification (props: IProps) {
  const list: Array<INotification> = useRecoilValue(notificationState.listAtom)
  // const [list, setList] = useState(list);
  const setList = useSetRecoilState(notificationState.listAtom);

  // useEffect(() => {

  // })

  // 将全部通知标记为已读
  const markAllNotificationAsRead = () => {
    let newList: any = Object.assign([], list);
    for (let j = 0; j < list.length; j++) {
      let tempRec = Object.assign({}, newList[j]);
      tempRec.hasRead = true
      newList[j] = tempRec;
    }

    setList(newList)
  }

  // 将单个通知标记为已读
  const markNotificationAsReadById = (id: string, e: MouseEvent<HTMLElement>) => {
    let newList: any = Object.assign([], list);
    for (let j = 0; j < list.length; j++) {
      let tempRec = Object.assign({}, newList[j]);
      if (tempRec.id === id) {
        tempRec.hasRead = true
      }
      newList[j] = tempRec;
    }

    // const newList = list.map((item: INotification) => {
    //   if (item.id === id) {
    //     item.hasRead = true
    //   }
    //   return item
    // })

    setList(newList)
  }

  return (
    <Fragment>
      <Card
        title="通知中心" 
        bordered={false}
        extra={
          <Button 
            disabled={list.every(item => item.hasRead === true)} 
            onClick={markAllNotificationAsRead}
          >
            全部标记为已读
          </Button>
        } 
      >
        <List
          itemLayout="horizontal"
          dataSource={list}
          renderItem={item => (
            <List.Item
              extra={
                item.hasRead 
                ? 
                null : 
                <Button 
                  onClick={ e => markNotificationAsReadById(item.id, e)}
                >
                  标记为已读
                </Button>}
            >
              <List.Item.Meta
                avatar={<Avatar src="https://joeschmoe.io/api/v1/random" />}
                title={<a href="https://ant.design"><Badge dot={!item.hasRead}>{item.title}</Badge></a>}
                description={item.desc}
              />
            </List.Item>
          )}
        />
      </Card>
    </Fragment>
  )
}

export default Notification